<template>
  <view class="normal-login-container">
    <view class="logo-content align-center justify-center flex">
      <image style="width: 100rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix">
      </image>
      <text class="title">智能分配号码</text>
    </view>
    <view class="login-form-content">
      <!-- 登录方式切换 -->
      <view class="login-type-switch">
        <view class="switch-item" :class="{ active: !isEmployeeIdLogin }" @click="switchToUsername">
          <text>用户名登录</text>
        </view>
        <view class="switch-item" :class="{ active: isEmployeeIdLogin }" @click="switchToEmployeeId">
          <text>工号登录</text>
        </view>
      </view>
      <view class="login-tip" v-if="showEmployeeIdTip && !isEmployeeIdLogin">
        <text class="tip-text">业务员使用工号登录</text>
      </view>
      <view class="input-item flex align-center">
        <view class="iconfont icon-user icon"></view>
        <input 
          v-model="loginForm.username" 
          class="input" 
          type="text" 
          :placeholder="isEmployeeIdLogin ? '请输入工号' : '请输入账号'" 
          maxlength="30"
          @focus="onUsernameFocus"
          @blur="onUsernameBlur"
        />
      </view>
    
      <view class="input-item flex align-center">
        <view class="iconfont icon-password icon"></view>
        <input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
      </view>
      <view class="remember-me-option flex align-center justify-between" style="width: 80%; margin: 10px auto;">
        <checkbox-group @change="toggleRememberMe">
          <label class="flex align-center remember-me-label">
            <checkbox :checked="rememberMe" value="rememberMe" color="#007aff" />
            <text class="remember-me-text">记住密码</text>
          </label>
        </checkbox-group>
      </view>
      <view class="input-item flex align-center" style="width: 60%;margin: 0px;" v-if="captchaEnabled">
        <view class="iconfont icon-code icon"></view>
        <input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
        <view class="login-code"> 
          <image :src="codeUrl" @click="getCode" class="login-code-img"></image>
        </view>
      </view>
      <view class="action-btn">
        <button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">登录</button>
      </view>
      <view class="reg text-center" v-if="register">
        <text class="text-grey1">没有入职？</text>
        <text @click="handleUserRegister" class="text-blue">立即入职</text>
      </view>
      <!-- <view class="xieyi text-center">
        <text class="text-grey1">登录即代表同意</text>
        <text @click="handleUserAgrement" class="text-blue">《用户协议》</text>
        <text @click="handlePrivacy" class="text-blue">《隐私协议》</text>
      </view> -->
    </view>
     
  </view>
</template>

<script>
  import { getCodeImg } from '@/api/login'
  import { updateTabBarByRole } from '@/utils/tabBar'

  export default {
    data() {
      return {
        codeUrl: "",
        captchaEnabled: true,
        // 用户注册开关
        register: true,
        globalConfig: getApp().globalData.config,
        loginForm: {
          username: "",
          password: "",
          code: "",
          uuid: ""
        },
        rememberMe: false,
        showEmployeeIdTip: false,
        isEmployeeIdLogin: false
      }
    },
    created() {
      this.getCode()
      // 尝试从本地存储读取记住的用户名和密码
      const rememberedUsername = uni.getStorageSync('rememberedUsername')
      const rememberedPassword = uni.getStorageSync('rememberedPassword')
      const rememberedMe = uni.getStorageSync('rememberMe')
      const rememberedLoginType = uni.getStorageSync('rememberedLoginType')

      if (rememberedUsername && rememberedPassword && rememberedMe) {
        this.loginForm.username = rememberedUsername
        this.loginForm.password = rememberedPassword
        this.rememberMe = rememberedMe
        // 恢复登录方式
        if (rememberedLoginType === 'employeeId') {
          this.isEmployeeIdLogin = true
        }
      }
      
      // 检查是否已有有效token，如果有则自动登录
      this.checkAutoLogin()
    },
    methods: {
      // 用户注册
      handleUserRegister() {
        this.$tab.redirectTo(`/pages/register`)
      },
      // 隐私协议
      handlePrivacy() {
        let site = this.globalConfig.appInfo.agreements[0]
        this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
      },
      // 用户协议
      handleUserAgrement() {
        let site = this.globalConfig.appInfo.agreements[1]
        this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
      },
      // 获取图形验证码
      getCode() {
        getCodeImg().then(res => {
          this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
          if (this.captchaEnabled) {
            this.codeUrl = 'data:image/gif;base64,' + res.img
            this.loginForm.uuid = res.uuid
          }
        })
      },
      // 登录方法
      async handleLogin() {
        if (this.loginForm.username === "") {
          const errorMsg = this.isEmployeeIdLogin ? "请输入工号" : "请输入账号"
          this.$modal.msgError(errorMsg)
        } else if (this.loginForm.password === "") {
          this.$modal.msgError("请输入密码")
        } else if (this.loginForm.code === "" && this.captchaEnabled) {
          this.$modal.msgError("请输入验证码")
        } else {
          this.$modal.loading("登录中，请耐心等待...")
          this.pwdLogin()
        }
      },
      // 密码登录
      async pwdLogin() {
        this.$store.dispatch('Login', this.loginForm).then(() => {
          this.$modal.closeLoading()
          // 根据记住密码状态进行存储或清除
          if (this.rememberMe) {
            uni.setStorageSync('rememberedUsername', this.loginForm.username)
            uni.setStorageSync('rememberedPassword', this.loginForm.password)
            uni.setStorageSync('rememberMe', true)
            uni.setStorageSync('rememberedLoginType', this.isEmployeeIdLogin ? 'employeeId' : 'username')
          } else {
            uni.removeStorageSync('rememberedUsername')
            uni.removeStorageSync('rememberedPassword')
            uni.removeStorageSync('rememberMe')
            uni.removeStorageSync('rememberedLoginType')
          }
          this.loginSuccess()
        }).catch(() => {
          if (this.captchaEnabled) {
            this.getCode()
          }
        })
      },
      // 登录成功后，处理函数
      async loginSuccess() {
  // 1) 拉取用户详情，并拿到它的 roles 列表
  let roles = []
  try {
    const userInfo = await this.$store.dispatch('GetInfo')
          // 存储用户角色
	  uni.setStorageSync('roles', userInfo.roles || [])
          // 存储完整用户信息
          uni.setStorageSync('userInfo', userInfo)
          console.log('存储的用户信息：', userInfo)
          console.log('存储的用户名：', userInfo.userName)
    roles = Array.isArray(userInfo.roles) ? userInfo.roles : []

  // 2) 判断是否包含 'yewuyuan'
  const isDJ = roles.includes('yewuyuan')

          // 3) 根据角色跳转到不同页面
  if (isDJ) {
            // 业务员跳转到首页
    this.$tab.reLaunch('/pages/index')
  } else {
            // 非业务员直接跳转到工作页面
    this.$tab.reLaunch('/pages/work/index')
  }

          // 4) 更新 tabBar 显示
          updateTabBarByRole(roles)

        } catch (err) {
          console.error('GetInfo 出错：', err)
        }
      },
      toggleRememberMe(e) {
        this.rememberMe = e.detail.value.includes('rememberMe')
        console.log('记住密码状态变更为:', this.rememberMe)
        console.log('事件详细信息:', e.detail.value)
      },
      // 检查自动登录
      async checkAutoLogin() {
        const token = this.$store.state.user.token
        if (token) {
          try {
            this.$modal.loading("正在自动登录...")
            // 验证token是否有效
            const userInfo = await this.$store.dispatch('GetInfo')
            if (userInfo) {
              // 存储用户角色
              uni.setStorageSync('roles', userInfo.roles || [])
              // 存储完整用户信息
              uni.setStorageSync('userInfo', userInfo)
              console.log('自动登录成功，用户信息：', userInfo)
              
              // 根据角色跳转到不同页面
              const roles = Array.isArray(userInfo.roles) ? userInfo.roles : []
              const isDJ = roles.includes('yewuyuan')
              
              if (isDJ) {
                // 业务员跳转到首页
                this.$tab.reLaunch('/pages/index')
              } else {
                // 非业务员直接跳转到工作页面
                this.$tab.reLaunch('/pages/work/index')
              }
              
              // 更新 tabBar 显示
              updateTabBarByRole(roles)
            }
            this.$modal.closeLoading()
          } catch (error) {
            console.log('自动登录失败，需要重新登录：', error)
            // token无效，清除token
            this.$store.commit('SET_TOKEN', '')
            uni.removeStorageSync('App-Token')
            this.$modal.closeLoading()
          }
        }
      },
      // 用户名输入框获得焦点
      onUsernameFocus() {
        this.showEmployeeIdTip = true
      },
      // 用户名输入框失去焦点
      onUsernameBlur() {
        // 延迟隐藏提示，给用户时间看到提示
        setTimeout(() => {
          this.showEmployeeIdTip = false
        }, 2000)
      },
      // 切换到用户名登录
      switchToUsername() {
        this.isEmployeeIdLogin = false
        this.loginForm.username = ''
        this.showEmployeeIdTip = false
      },
      // 切换到工号登录
      switchToEmployeeId() {
        this.isEmployeeIdLogin = true
        this.loginForm.username = ''
        this.showEmployeeIdTip = false
      }
    }
  }
</script>

<style lang="scss" scoped>
  page {
    background-color: #ffffff;
  }

  .normal-login-container {
    width: 100%;

    .logo-content {
      width: 100%;
      font-size: 21px;
      text-align: center;
      padding-top: 15%;

      image {
        border-radius: 4px;
      }

      .title {
        margin-left: 10px;
      }
    }

    .login-form-content {
      text-align: center;
      margin: 20px auto;
      margin-top: 15%;
      width: 80%;

      .input-item {
        margin: 20px auto;
        background-color: #f5f6f7;
        height: 45px;
        border-radius: 20px;

        .icon {
          font-size: 38rpx;
          margin-left: 10px;
          color: #999;
        }

        .input {
          width: 100%;
          font-size: 14px;
          line-height: 20px;
          text-align: left;
          padding-left: 15px;
        }

      }

      .login-btn {
        margin-top: 40px;
        height: 45px;
      }
      
      .login-type-switch {
        display: flex;
        justify-content: center;
        margin-bottom: 30rpx;
        background-color: #f5f6f7;
        border-radius: 25rpx;
        padding: 4rpx;
        width: 80%;
        margin: 0 auto 30rpx auto;
        
        .switch-item {
          flex: 1;
          text-align: center;
          padding: 20rpx 0;
          border-radius: 20rpx;
          transition: all 0.3s ease;
          
          text {
            font-size: 28rpx;
            color: #666;
            transition: color 0.3s ease;
          }
          
          &.active {
            background-color: #007aff;
            
            text {
              color: #fff;
              font-weight: 500;
            }
          }
        }
      }
      
      .login-tip {
        text-align: center;
        margin: 10px auto;
        width: 80%;
        
        .tip-text {
          font-size: 24rpx;
          color: #007aff;
          background-color: rgba(0, 122, 255, 0.1);
          padding: 8rpx 16rpx;
          border-radius: 20rpx;
          border: 1px solid rgba(0, 122, 255, 0.3);
        }
      }
      
      .reg {
        margin-top: 15px;
      }
      
      .xieyi {
        color: #333;
        margin-top: 20px;
      }
      
      .login-code {
        height: 38px;
        float: right;
      
        .login-code-img {
          height: 38px;
          position: absolute;
          margin-left: 10px;
          width: 200rpx;
        }
      }
    }
  }

  .remember-me-option {
    margin-bottom: 20rpx;
    .remember-me-label {
      padding: 15rpx 0; /* Increase padding to further enlarge clickable area */
      line-height: 24rpx; /* Ensure text aligns well within the enlarged area */
    }
    .remember-me-text {
      font-size: 24rpx; /* 调整字体大小 */
      color: #606266; /* 调整颜色 */
      margin-left: 10rpx; /* 调整文字与复选框的间距 */
    }
    /* 自定义checkbox样式使其看起来像radio */
    uni-checkbox .uni-checkbox-input {
      border-radius: 50%; /* 使其变为圆形 */
      width: 32rpx; /* 调整大小 */
      height: 32rpx; /* 调整大小 */
      border-color: #c0c0c0; /* 默认边框颜色 */
    }

    uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked {
      background-color: #007aff; /* 选中时背景色为蓝色 */
      border-color: #007aff; /* 选中时边框颜色为蓝色 */
    }
    
    /* 隐藏默认对勾，创建自定义选中点 */
    uni-checkbox .uni-checkbox-input.uni-checkbox-input-checked::before {
      content: '';
      display: block;
      width: 16rpx; /* 内部圆点大小 */
      height: 16rpx;
      background-color: #ffffff; /* 内部圆点颜色 */
      border-radius: 50%;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
  }

</style>
